package com.suhe.ozon.job;

import com.suhe.ozon.entity.dto.PriceSyncDTO;
import com.suhe.ozon.entity.po.ClientPO;
import com.suhe.ozon.entity.po.ProductPO;
import com.suhe.ozon.http.PriceHttp;
import com.suhe.ozon.http.ProductHttp;
import com.suhe.ozon.service.ClientService;
import com.suhe.ozon.service.ProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * <p>
 * </p>
 *
 * @author liuning
 * @date 22:02 2024/1/20
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ProductSyncJob {

    private final ProductService productService;

    private final ClientService clientService;

    public void start() {
        start(null);
    }

    public void start(String clientId) {
        // 获取所有客户端
        final List<ClientPO> clientPOS = clientService.list().stream().filter(p -> p.getClientId().equals(clientId)).collect(Collectors.toList());
        clientPOS.forEach(client -> {
            List<ProductPO> productList = new CopyOnWriteArrayList<>();
            try {
                new ProductHttp().sync(client, 0, productList);
                final Map<String, PriceSyncDTO> priceMap = new PriceHttp().sync(client, null);
                productList.parallelStream().filter(p -> priceMap.containsKey(p.getOzonProductId())).forEach(p -> {
                    p.setMinPrice(priceMap.get(p.getOzonProductId()).getMinPrice())
                            .setAutoActionEnabled(priceMap.get(p.getOzonProductId()).isAutoActionEnabled());
                    productService.saveOrUpdate(p);
                });
            } catch (IOException e) {
                log.error("商品数据同步失败", e);
            }
        });
    }
}
